
// DaoImpl/MemberDaoImpl.java
package com.xxxy.ljh.myapplication.DaoImpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxxy.ljh.myapplication.Dao.MemberDao;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.Member;

import java.util.ArrayList;
import java.util.List;

/**
 * 成员数据访问接口实现类，用于操作社团成员相关的数据库表。
 */
public class MemberDaoImpl implements MemberDao {
    private sqliteDBHelper dbHelper;

    /**
     * 构造方法，初始化数据库帮助类实例。
     *
     * @param context 上下文对象，用于创建数据库连接
     */
    public MemberDaoImpl(Context context) {
        this.dbHelper = new sqliteDBHelper(context);
    }

    /**
     * 根据社团ID查询所有该社团的成员信息。
     *
     * @param associationId 社团ID
     * @return 返回该社团的所有成员列表
     */
    @Override
    public List<Member> getMembersByAssociationId(int associationId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<Member> members = new ArrayList<>();

        // 查询语句：关联用户表获取用户名、真实姓名和学号等信息
        String query = "SELECT am.*, u.username, u.real_name, u.student_id " +
                "FROM association_member am " +
                "JOIN t_user u ON am.user_id = u.user_id " +
                "WHERE am.association_id = ?";

        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(associationId)});

        while (cursor.moveToNext()) {
            Member member = new Member();
            member.setMemberId(cursor.getInt(cursor.getColumnIndexOrThrow("member_id")));
            member.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            member.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            member.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            member.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            member.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            member.setMemberRole(cursor.getInt(cursor.getColumnIndexOrThrow("member_role")));
            member.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")));
            member.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow("create_time")));
            member.setExitTime(cursor.getString(cursor.getColumnIndexOrThrow("exit_time")));
            member.setExitReason(cursor.getString(cursor.getColumnIndexOrThrow("exit_reason")));
            members.add(member);
        }
        cursor.close();
        return members;
    }

    /**
     * 获取指定社团中待审核（status=0）的成员列表。
     *
     * @param associationId 社团ID
     * @return 待审核成员列表
     */
    @Override
    public List<Member> getPendingMembersByAssociationId(int associationId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<Member> members = new ArrayList<>();

        // 查询语句：只筛选状态为0（待审核）的成员记录
        String query = "SELECT am.*, u.username, u.real_name, u.student_id " +
                "FROM association_member am " +
                "JOIN t_user u ON am.user_id = u.user_id " +
                "WHERE am.association_id = ? AND am.status = 0";

        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(associationId)});

        while (cursor.moveToNext()) {
            Member member = new Member();
            member.setMemberId(cursor.getInt(cursor.getColumnIndexOrThrow("member_id")));
            member.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            member.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            member.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            member.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            member.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            member.setMemberRole(cursor.getInt(cursor.getColumnIndexOrThrow("member_role")));
            member.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")));
            member.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow("create_time")));
            members.add(member);
        }
        cursor.close();
        return members;
    }

    /**
     * 搜索指定社团中的成员，支持按姓名或用户名模糊匹配。
     *
     * @param associationId 社团ID
     * @param keyword       搜索关键词
     * @return 匹配到的成员列表
     */
    @Override
    public List<Member> searchMembersByAssociationId(int associationId, String keyword) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<Member> members = new ArrayList<>();

        // 查询语句：通过LIKE进行模糊搜索
        String query = "SELECT am.*, u.username, u.real_name, u.student_id " +
                "FROM association_member am " +
                "JOIN t_user u ON am.user_id = u.user_id " +
                "WHERE am.association_id = ? AND (u.real_name LIKE ? OR u.username LIKE ?)";

        String searchKeyword = "%" + keyword + "%";
        Cursor cursor = db.rawQuery(query, new String[]{
                String.valueOf(associationId), searchKeyword, searchKeyword});

        while (cursor.moveToNext()) {
            Member member = new Member();
            member.setMemberId(cursor.getInt(cursor.getColumnIndexOrThrow("member_id")));
            member.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            member.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            member.setUserName(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            member.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            member.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            member.setMemberRole(cursor.getInt(cursor.getColumnIndexOrThrow("member_role")));
            member.setStatus(cursor.getInt(cursor.getColumnIndexOrThrow("status")));
            member.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow("create_time")));
            members.add(member);
        }
        cursor.close();
        return members;
    }

    /**
     * 更新成员的状态字段。
     *
     * @param memberId 成员ID
     * @param status   新的状态值
     * @return 受影响的行数
     */
    @Override
    public int updateMemberStatus(int memberId, int status) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("status", status);

        return db.update("association_member", values, "member_id = ?",
                new String[]{String.valueOf(memberId)});
    }

    /**
     * 添加一个新的社团成员记录。
     *
     * @param member 成员实体对象，包含要插入的数据
     * @return 插入后的主键ID
     */
    @Override
    public int addMember(Member member) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("association_id", member.getAssociationId());
        values.put("user_id", member.getUserId());
        values.put("member_role", member.getMemberRole());
        values.put("status", member.getStatus());
        values.put("create_time", member.getCreateTime());

        return (int) db.insert("association_member", null, values);
    }

    /**
     * 移除一个社团成员，并设置退出时间和原因。
     *
     * @param memberId   要移除的成员ID
     * @param exitReason 退出原因描述
     * @return 受影响的行数
     */
    @Override
    public int removeMember(int memberId, String exitReason) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("status", 2); // 已退出状态
        values.put("exit_time", String.valueOf(System.currentTimeMillis() / 1000));
        values.put("exit_reason", exitReason);

        return db.update("association_member", values, "member_id = ?",
                new String[]{String.valueOf(memberId)});
    }
}